{% extends "base.html" %}

{% block title %}仪表板 - MinerU 文档解析系统{% endblock %}

{% block page_title %}仪表板{% endblock %}

{% block content %}
<div class="fade-in">
    <!-- 统计卡片 -->
    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
        <div class="bg-white rounded-xl shadow-sm p-6 hover-scale">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-sm text-gray-500 mb-1">今日解析</p>
                    <p class="text-2xl font-bold text-gray-800">{{ stats.tasks.today }}</p>
                    <p class="text-sm {% if stats.tasks.today_growth_rate > 0 %}text-green-600{% elif stats.tasks.today_growth_rate < 0 %}text-red-600{% else %}text-gray-600{% endif %} mt-1">
                        {% if stats.tasks.today_growth_rate > 0 %}
                            <i class="fas fa-arrow-up"></i> {{ stats.tasks.today_growth_rate }}%
                        {% elif stats.tasks.today_growth_rate < 0 %}
                            <i class="fas fa-arrow-down"></i> {{ stats.tasks.today_growth_rate|abs }}%
                        {% else %}
                            <i class="fas fa-minus"></i> 0%
                        {% endif %}
                    </p>
                </div>
                <div class="w-12 h-12 bg-blue-100 rounded-lg flex items-center justify-center">
                    <i class="fas fa-file-alt text-blue-600 text-xl"></i>
                </div>
            </div>
        </div>
        
        <div class="bg-white rounded-xl shadow-sm p-6 hover-scale">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-sm text-gray-500 mb-1">进行中任务</p>
                    <p class="text-2xl font-bold text-gray-800">{{ stats.tasks.processing }}</p>
                    <p class="text-sm {% if stats.tasks.recent_processing > 0 %}text-green-600{% else %}text-gray-600{% endif %} mt-1">
                        {% if stats.tasks.recent_processing > 0 %}
                            <i class="fas fa-plus"></i> 最近1小时新增 {{ stats.tasks.recent_processing }} 个
                        {% else %}
                            <i class="fas fa-clock"></i> 暂无新增
                        {% endif %}
                    </p>
                </div>
                <div class="w-12 h-12 bg-orange-100 rounded-lg flex items-center justify-center">
                    <i class="fas fa-clock text-orange-600 text-xl"></i>
                </div>
            </div>
        </div>
        
        <div class="bg-white rounded-xl shadow-sm p-6 hover-scale">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-sm text-gray-500 mb-1">活跃用户</p>
                    <p class="text-2xl font-bold text-gray-800">{{ stats.users.active }}</p>
                    <p class="text-sm text-green-600 mt-1">
                        <i class="fas fa-arrow-up"></i> 8%
                    </p>
                </div>
                <div class="w-12 h-12 bg-green-100 rounded-lg flex items-center justify-center">
                    <i class="fas fa-users text-green-600 text-xl"></i>
                </div>
            </div>
        </div>
        
        <div class="bg-white rounded-xl shadow-sm p-6 hover-scale">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-sm text-gray-500 mb-1">系统状态</p>
                    <p class="text-2xl font-bold text-gray-800">{{ stats.system.status }}</p>
                    <p class="text-sm {% if stats.system.status == '良好' %}text-green-600{% elif stats.system.status == '正常' %}text-blue-600{% elif stats.system.status == '繁忙' %}text-orange-600{% else %}text-gray-600{% endif %} mt-1">
                        <i class="fas fa-{% if stats.system.status == '良好' %}check-circle{% elif stats.system.status == '正常' %}check-circle{% elif stats.system.status == '繁忙' %}exclamation-triangle{% else %}question-circle{% endif %}"></i> {{ stats.system.uptime }}
                    </p>
                </div>
                <div class="w-12 h-12 bg-green-100 rounded-lg flex items-center justify-center">
                    <i class="fas fa-server text-green-600 text-xl"></i>
                </div>
            </div>
        </div>
    </div>
    
    <!-- 图表区域 -->
    <div class="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-8">
        <div class="bg-white rounded-xl shadow-sm p-6">
            <h3 class="text-lg font-semibold text-gray-800 mb-4">解析统计（最近7天）</h3>
            <div class="h-64">
                <canvas id="parseChart"></canvas>
            </div>
            <div class="mt-4 grid grid-cols-3 gap-4 text-center">
                <div class="bg-blue-50 p-3 rounded-lg">
                    <div class="text-2xl font-bold text-blue-600" id="totalWeekTasks">0</div>
                    <div class="text-sm text-gray-600">总任务数</div>
                </div>
                <div class="bg-green-50 p-3 rounded-lg">
                    <div class="text-2xl font-bold text-green-600" id="completedWeekTasks">0</div>
                    <div class="text-sm text-gray-600">成功数</div>
                </div>
                <div class="bg-red-50 p-3 rounded-lg">
                    <div class="text-2xl font-bold text-red-600" id="failedWeekTasks">0</div>
                    <div class="text-sm text-gray-600">失败数</div>
                </div>
            </div>
        </div>
        
        <div class="bg-white rounded-xl shadow-sm p-6">
            <h3 class="text-lg font-semibold text-gray-800 mb-4">系统资源</h3>
            <div class="space-y-4">
                <div>
                    <div class="flex justify-between items-center mb-2">
                        <span class="text-sm text-gray-600">CPU 使用率</span>
                        <span class="text-sm text-gray-800" id="cpu-value">加载中...</span>
                    </div>
                    <div class="w-full bg-gray-200 rounded-full h-2">
                        <div class="bg-blue-600 h-2 rounded-full transition-all duration-300" id="cpu-bar" style="width: 0%"></div>
                    </div>
                </div>
                <div>
                    <div class="flex justify-between items-center mb-2">
                        <span class="text-sm text-gray-600">内存使用率</span>
                        <span class="text-sm text-gray-800" id="memory-value">加载中...</span>
                    </div>
                    <div class="w-full bg-gray-200 rounded-full h-2">
                        <div class="bg-green-600 h-2 rounded-full transition-all duration-300" id="memory-bar" style="width: 0%"></div>
                    </div>
                </div>
                <div>
                    <div class="flex justify-between items-center mb-2">
                        <span class="text-sm text-gray-600">磁盘使用率</span>
                        <span class="text-sm text-gray-800" id="disk-value">加载中...</span>
                    </div>
                    <div class="w-full bg-gray-200 rounded-full h-2">
                        <div class="bg-orange-600 h-2 rounded-full transition-all duration-300" id="disk-bar" style="width: 0%"></div>
                    </div>
                </div>
                <div class="mt-4 pt-4 border-t">
                    <div class="flex justify-between items-center">
                        <span class="text-sm text-gray-600">系统状态</span>
                        <span class="text-sm font-medium" id="system-status">加载中...</span>
                    </div>
                    <div class="flex justify-between items-center mt-2">
                        <span class="text-sm text-gray-600">运行时间</span>
                        <span class="text-sm text-gray-800" id="uptime">加载中...</span>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <!-- 最近任务 -->
    <div class="bg-white rounded-xl shadow-sm p-6">
        <div class="flex justify-between items-center mb-6">
            <h3 class="text-lg font-semibold text-gray-800">最近任务</h3>
            <a href="/web/tasks?token={{ token }}" class="text-blue-600 hover:text-blue-800 text-sm">查看全部</a>
        </div>
        
        <div class="overflow-x-auto">
            <table class="w-full">
                <thead>
                    <tr class="border-b">
                        <th class="text-left py-3 px-4 text-sm font-medium text-gray-600">任务ID</th>
                        <th class="text-left py-3 px-4 text-sm font-medium text-gray-600">文件名</th>
                        <th class="text-left py-3 px-4 text-sm font-medium text-gray-600">状态</th>
                        <th class="text-left py-3 px-4 text-sm font-medium text-gray-600">进度</th>
                        <th class="text-left py-3 px-4 text-sm font-medium text-gray-600">创建时间</th>
                    </tr>
                </thead>
                <tbody id="recentTasks">
                    <tr class="border-b hover:bg-gray-50">
                        <td class="py-3 px-4 text-sm text-gray-800" colspan="5">
                            <div class="text-center py-8">
                                <i class="fas fa-spinner fa-spin text-2xl text-gray-400 mb-2"></i>
                                <p class="text-gray-500">加载中...</p>
                            </div>
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- 隐藏的统计数据存储 -->
<div id="weekStats" style="display: none;">
    {{ stats.week_stats|tojson }}
</div>
{% endblock %}

{% block extra_js %}
<script src="/static/vendor/js/chart-4.5.0.js"></script>
<script>
// 页面加载时获取最近任务和系统监控数据
document.addEventListener('DOMContentLoaded', async function() {
    await loadRecentTasks();
    await loadSystemMetrics();
    await initParseChart();
    
    // 启动定时刷新
    startSystemMetricsRefresh();
    startRecentTasksRefresh();
});

// 初始化解析统计图表
async function initParseChart() {
    try {
        // 获取最近7天的统计数据
        const weekStatsElement = document.getElementById('weekStats');
        if (!weekStatsElement) return;
        
        const weekStats = JSON.parse(weekStatsElement.textContent);
        if (!weekStats || weekStats.length === 0) return;
        
        // 计算统计数据
        let totalTasks = 0;
        let completedTasks = 0;
        let failedTasks = 0;
        
        const labels = weekStats.map(stat => {
            const date = new Date(stat.date);
            return date.toLocaleDateString('zh-CN', { month: 'short', day: 'numeric' });
        });
        
        const taskData = weekStats.map(stat => {
            totalTasks += stat.tasks;
            completedTasks += stat.completed;
            failedTasks += stat.failed;
            return stat.tasks;
        });
        
        const completedData = weekStats.map(stat => stat.completed);
        const failedData = weekStats.map(stat => stat.failed);
        
        // 更新统计数字
        document.getElementById('totalWeekTasks').textContent = totalTasks;
        document.getElementById('completedWeekTasks').textContent = completedTasks;
        document.getElementById('failedWeekTasks').textContent = failedTasks;
        
        // 创建图表
        const ctx = document.getElementById('parseChart').getContext('2d');
        new Chart(ctx, {
            type: 'line',
            data: {
                labels: labels,
                datasets: [{
                    label: '总任务数',
                    data: taskData,
                    borderColor: 'rgb(59, 130, 246)',
                    backgroundColor: 'rgba(59, 130, 246, 0.1)',
                    tension: 0.4,
                    fill: true
                }, {
                    label: '成功数',
                    data: completedData,
                    borderColor: 'rgb(34, 197, 94)',
                    backgroundColor: 'rgba(34, 197, 94, 0.1)',
                    tension: 0.4,
                    fill: false
                }, {
                    label: '失败数',
                    data: failedData,
                    borderColor: 'rgb(239, 68, 68)',
                    backgroundColor: 'rgba(239, 68, 68, 0.1)',
                    tension: 0.4,
                    fill: false
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        position: 'top',
                    },
                    title: {
                        display: false
                    }
                },
                scales: {
                    y: {
                        beginAtZero: true,
                        ticks: {
                            stepSize: 1
                        }
                    }
                },
                interaction: {
                    intersect: false,
                    mode: 'index'
                }
            }
        });
        
    } catch (error) {
        console.error('初始化图表失败:', error);
    }
}

async function loadRecentTasks() {
    try {
        const tasks = await apiRequest('/api/v1/tasks/my-tasks?page_size=5');
        const tbody = document.getElementById('recentTasks');
        
        if (tasks && tasks.items && tasks.items.length > 0) {
            tbody.innerHTML = tasks.items.map(task => `
                <tr class="border-b hover:bg-gray-50">
                    <td class="py-3 px-4 text-sm text-gray-800">${task.task_id}</td>
                    <td class="py-3 px-4 text-sm text-gray-800">${task.filename}</td>
                    <td class="py-3 px-4">
                        <span class="status-badge status-${task.status}">
                            <i class="fas fa-${getStatusIcon(task.status)} mr-1"></i>
                            ${getStatusText(task.status)}
                        </span>
                    </td>
                    <td class="py-3 px-4">
                        <div class="w-full bg-gray-200 rounded-full h-2">
                            <div class="bg-${getStatusColor(task.status)}-600 h-2 rounded-full" style="width: ${task.progress}%"></div>
                        </div>
                    </td>
                    <td class="py-3 px-4 text-sm text-gray-600">${formatDate(task.created_at)}</td>
                </tr>
            `).join('');
        } else {
            tbody.innerHTML = `
                <tr class="border-b hover:bg-gray-50">
                    <td class="py-3 px-4 text-sm text-gray-800" colspan="5">
                        <div class="text-center py-8">
                            <i class="fas fa-inbox text-2xl text-gray-400 mb-2"></i>
                            <p class="text-gray-500">暂无任务</p>
                        </div>
                    </td>
                </tr>
            `;
        }
    } catch (error) {
        console.error('加载任务失败:', error);
        document.getElementById('recentTasks').innerHTML = `
            <tr class="border-b hover:bg-gray-50">
                <td class="py-3 px-4 text-sm text-gray-800" colspan="5">
                    <div class="text-center py-8">
                        <i class="fas fa-exclamation-triangle text-2xl text-gray-400 mb-2"></i>
                        <p class="text-gray-500">加载失败</p>
                    </div>
                </td>
            </tr>
        `;
    }
}

function getStatusIcon(status) {
    const icons = {
        'pending': 'clock',
        'processing': 'spinner fa-spin',
        'completed': 'check-circle',
        'failed': 'times-circle'
    };
    return icons[status] || 'question-circle';
}

function getStatusText(status) {
    const texts = {
        'pending': '等待中',
        'processing': '处理中',
        'completed': '完成',
        'failed': '失败'
    };
    return texts[status] || '未知';
}

function getStatusColor(status) {
    const colors = {
        'pending': 'orange',
        'processing': 'blue',
        'completed': 'green',
        'failed': 'red'
    };
    return colors[status] || 'gray';
}

// 系统监控相关函数
let metricsInterval = null;
let tasksInterval = null;

async function loadSystemMetrics() {
    try {
        const metrics = await apiRequest('/api/v1/system/metrics/simple');
        
        // 更新CPU使用率
        const cpuValue = metrics.cpu.toFixed(1);
        document.getElementById('cpu-value').textContent = cpuValue + '%';
        document.getElementById('cpu-bar').style.width = cpuValue + '%';
        
        // 更新内存使用率
        const memoryValue = metrics.memory.toFixed(1);
        document.getElementById('memory-value').textContent = memoryValue + '%';
        document.getElementById('memory-bar').style.width = memoryValue + '%';
        
        // 更新磁盘使用率
        const diskValue = metrics.disk.toFixed(1);
        document.getElementById('disk-value').textContent = diskValue + '%';
        document.getElementById('disk-bar').style.width = diskValue + '%';
        
        // 更新系统状态
        const statusElement = document.getElementById('system-status');
        statusElement.textContent = metrics.status;
        statusElement.className = 'text-sm font-medium ' + getStatusColorClass(metrics.status);
        
        // 更新运行时间（如果有）
        if (metrics.formatted_uptime) {
            document.getElementById('uptime').textContent = metrics.formatted_uptime;
        }
        
        // 添加动态效果
        animateMetricsChange();
        
    } catch (error) {
        console.error('加载系统监控数据失败:', error);
        // 显示错误状态
        document.getElementById('cpu-value').textContent = '错误';
        document.getElementById('memory-value').textContent = '错误';
        document.getElementById('disk-value').textContent = '错误';
        document.getElementById('system-status').textContent = '离线';
        document.getElementById('uptime').textContent = '未知';
    }
}

function getStatusColorClass(status) {
    const colorClasses = {
        '良好': 'text-green-600',
        '正常': 'text-blue-600',
        '繁忙': 'text-orange-600',
        '未知': 'text-gray-600'
    };
    return colorClasses[status] || 'text-gray-600';
}

function animateMetricsChange() {
    // 为进度条添加脉冲效果
    const bars = ['cpu-bar', 'memory-bar', 'disk-bar'];
    bars.forEach(barId => {
        const bar = document.getElementById(barId);
        bar.style.transform = 'scale(1.05)';
        setTimeout(() => {
            bar.style.transform = 'scale(1)';
        }, 200);
    });
}

function startSystemMetricsRefresh() {
    // 每5秒刷新一次系统监控数据（降低频率以提高性能）
    metricsInterval = setInterval(async () => {
        await loadSystemMetrics();
    }, 5000);
}

function startRecentTasksRefresh() {
    // 每15秒刷新一次最近任务（降低频率以提高性能）
    tasksInterval = setInterval(async () => {
        await loadRecentTasks();
    }, 15000);
}

// 页面卸载时清理定时器
window.addEventListener('beforeunload', () => {
    if (metricsInterval) {
        clearInterval(metricsInterval);
    }
    if (tasksInterval) {
        clearInterval(tasksInterval);
    }
});

// 页面可见性变化时处理定时器
document.addEventListener('visibilitychange', () => {
    if (document.hidden) {
        // 页面隐藏时停止定时器
        if (metricsInterval) {
            clearInterval(metricsInterval);
            metricsInterval = null;
        }
        if (tasksInterval) {
            clearInterval(tasksInterval);
            tasksInterval = null;
        }
    } else {
        // 页面显示时重新启动定时器
        startSystemMetricsRefresh();
        startRecentTasksRefresh();
    }
});
</script>
{% endblock %}